package firstcontent.gc;

/**
 * @Author: fxy
 * @Date: 2022/02/23/8:39
 * @Description:
 */
public class CanReliveObj {
    /**
     * 类变量，属于gc root
     */
    public static CanReliveObj obj;

    /**
     * 只能被调用一次
     * @throws Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("调用当前类重写的finalize()方法");
        obj = this;
    }

    public static void main(String[] args) {
        try{
            obj = new CanReliveObj();
            //对象第一次成功拯救自己
            obj = null;
            System.gc();
            System.out.println("第一次 gc");
            Thread.sleep(2000);
            if(obj==null){
                System.out.println("obj is dead");
            }else {
                System.out.println("obj is alive");
            }
            System.out.println("第二次 gc");
            obj = null;
            System.gc();
            Thread.sleep(2000);
            if(obj==null){
                System.out.println("obj is dead");
            }else {
                System.out.println("obj is alive");
            }
        }catch (Exception e){

        }
    }
}
